import { useEffect, useState } from "react"
import { Button, message, Modal, Radio, Tabs } from "antd"
import { DeleteOutlined } from '@ant-design/icons'

import {
  queryPrivileges,
  queryPrivilegeUsers,
  createPrivilegeUser,
  deletePrivilegeUser,
  createPrivilegeGroup,
  deletePrivilegeGroup
} from "../../apis/privilege"

import CommonTable from "../../components/common/CommonTable"
import UserPicker from "../../components/UserPicker"
import GroupPicker from "../../components/GroupPicker"


const Privilege = () => {
  const [privileges, setPrivileges] = useState([])
  const [curPid, setCurPid] = useState('')
  const [loading, setLoading] = useState('')
  const [users, setUsers] = useState([])
  const [groups, setGroups] = useState([])

  const doQueryPrivileges = async () => {
    const data = await queryPrivileges()
    setPrivileges(data)
  }

  const doQueryPrivilegeUsers = async () => {
    if (!loading) {
      setLoading(true)
      try {
        const data = await queryPrivilegeUsers({
          privilegeId: curPid
        })
        setUsers(data.users || [])
        setGroups(data.groups || [])
        setLoading(false)
      } catch (error) {
        setLoading(false)
      }
    }
  }

  const handlePickUser = async (userIds) => {
    try {
      for (let el of userIds) {
        await createPrivilegeUser({
          privilegeId: curPid,
          userId: el
        })
      }
      message.success('添加用户成功')
      doQueryPrivilegeUsers()
    } catch (error) {
      message.error('添加用户失败')
    }
  }

  const handlePickGroup = async (groupIds) => {
    try {
      for (let el of groupIds) {
        await createPrivilegeGroup({
          privilegeId: curPid,
          groupId: el
        })
      }
      message.success('添加用户组成功')
      doQueryPrivilegeUsers()
    } catch (error) {
      message.error('添加用户组失败')
    }
  }

  const handleDeleteUser = (userId) => {
    Modal.confirm({
      title: '确定要删除？',
      onOk: async () => {
        try {
          await deletePrivilegeUser({
            privilegeId: curPid,
            userId
          })
          message.success('删除用户成功')
          doQueryPrivilegeUsers()
        } catch (error) {
          message.error('删除用户失败')
        }
      }
    })
  }

  const handleDeleteGroup = (groupId) => {
    Modal.confirm({
      title: '确定要删除？',
      onOk: async () => {
        try {
          await deletePrivilegeGroup({
            privilegeId: curPid,
            groupId
          })
          message.success('删除用户组成功')
          doQueryPrivilegeUsers()
        } catch (error) {
          message.error('删除用户组失败')
        }
      }
    })
  }

  useEffect(() => {
    doQueryPrivileges()
  }, [])

  useEffect(() => {
    if (curPid) {
      doQueryPrivilegeUsers()
    }
  }, [curPid])

  useEffect(() => {
    if (privileges.length) {
      setCurPid(privileges[0].id)
    }
  }, [privileges])

  const userTableColumns = [
    {
      key: 'id',
      dataIndex: 'id',
      title: '用户id',
      width: 100,
      sorter: true
    },
    {
      key: 'fullName',
      dataIndex: 'fullName',
      title: '名称',
      width: 200
    },
    {
      key: 'email',
      dataIndex: 'email',
      title: '邮箱',
      sorter: true
    },
    {
      key: 'tenantId',
      dataIndex: 'tenantId',
      title: '租户',
      width: 120
    },
    {
      key: 'action',
      title: '操作',
      width: 80,
      align: 'center',
      render: (rowData) => {
        return <Button
          size="small"
          type="primary"
          danger
          onClick={() => {
            handleDeleteUser(rowData.id)
          }}
        ><DeleteOutlined /></Button>
      },
    }
  ]
  const groupTableColumns = [
    {
      key: 'id',
      dataIndex: 'id',
      title: '用户组ID',
      width: 100
    },
    {
      key: 'name',
      dataIndex: 'name',
      title: '组名'
    },
    {
      key: 'action',
      title: '操作',
      width: 80,
      align: 'center',
      render: (rowData) => {
        return <Button
          size="small"
          type="primary"
          danger
          onClick={() => {
            handleDeleteGroup(rowData.id)
          }}
        ><DeleteOutlined /></Button>
      },
    }
  ]

  return <div className="page-wrap">
    <div className="page-head" style={{ height: 32 }}>
      <Radio.Group
        optionType="button"
        buttonStyle="solid"
        options={privileges.map(el => ({
          value: el.id,
          label: `访问 ${el.name.replace('access-', '')} 应用`
        }))}
        value={curPid}
        onChange={(e) => {
          setCurPid(e.target.value)
        }}
      ></Radio.Group>
    </div>
    <div className="page-body">
      <Tabs type="card">
        <Tabs.TabPane key="user" tab="用户">
          <div className="page-wrap" style={{ height: 'calc(100vh - 180px)' }}>
            <div className="page-head">
              <UserPicker
                onPick={handlePickUser}
                disabledKeys={users.map(el => el.id)}
              ></UserPicker>
            </div>
            <div className="page-body">
              <CommonTable
                dataSource={users}
                columns={userTableColumns}
                loading={loading}
              ></CommonTable>
            </div>
          </div>
        </Tabs.TabPane>
        <Tabs.TabPane key="group" tab="用户组">
          <div className="page-wrap" style={{ height: 'calc(100vh - 180px)' }}>
            <div className="page-head">
              <GroupPicker
                onPick={handlePickGroup}
                disabledKeys={groups.map(el => el.id)}
              ></GroupPicker>
            </div>
            <div className="page-body">
              <CommonTable
                dataSource={groups}
                columns={groupTableColumns}
                loading={loading}
              ></CommonTable>
            </div>
          </div>
        </Tabs.TabPane>
      </Tabs>
    </div>
  </div>
}

export default Privilege